package com.lottery.common.thread;


import com.alibaba.fastjson.JSON;
import com.lottery.common.service.SmsMssageService;
import lombok.extern.slf4j.Slf4j;
import org.nutz.lang.util.NutMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.*;

@Slf4j
@Service
public class SendMsgTool {
	private static SendMsgTool instance;
	private ExecutorService threadPool;// 线程池
	private BlockingDeque<NutMap> queue = new LinkedBlockingDeque<NutMap>(1000);// 待执行的任务队列


	@Autowired
	private  SmsMssageService smsMssageService;

	public static SendMsgTool getInstance() {
		if (instance == null) {
			instance = new SendMsgTool();
			instance.threadPool = new ThreadPoolExecutor(5,
					10,
					100,
					TimeUnit.MICROSECONDS,
					new LinkedBlockingQueue<Runnable>());
		}
		return instance;
	}

	private SendMsgTool() {
	}

//	public void setSmsMssageService(SmsMssageService smsMssageService) {
//		SendMsgTool.smsMssageService = smsMssageService;
//	}

	@PostConstruct
	public void init(){
		SendMsgTool.getInstance().execute();
		instance.smsMssageService = this.smsMssageService;

	}


	/**
	 * 添加待执行任务
	 *
	 * @param nutMap
	 */
	public void addSend(NutMap nutMap) {
		queue.add(nutMap);
	}


	class ActivateTask implements Runnable {
		private NutMap nutMap;

		public ActivateTask(NutMap nutMap) {
			this.nutMap = nutMap;
		}

		@Override
		public void run() {
			try {
				log.info("nutMap={}", JSON.toJSONString(nutMap));
				smsMssageService.sendMsg(nutMap);
				log.info("send sms successfully");
			} catch (Exception e) {
				e.printStackTrace();
				log.info("send sms failed");
			}
		}


	}


	public void execute() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					try {
						NutMap nutMap = queue.take();
						if (nutMap == null) {
							continue;
						}
						threadPool.execute(new ActivateTask(nutMap));
					} catch (Exception e) {
						log.info("短信发送线程池启动异常");
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

}
